;

//无刷新上传图片
var upload = {
    error: function (msg) {
        common_ops.alert(msg);
    },
    success: function (file_key) {
        if (!file_key) {
            return false
        }
        var html = '<img src="' + common_ops.buildPictureUrl(file_key) + '"/>'
            + '<span class="fa fa-times-circle del del_image" data="' + file_key + '"></span>';
        //size() 方法返回被 jQuery 选择器匹配的元素的数量
        if ($(".upload_pic_wrap .pic-each").size() > 0) {
            $('.upload_pic_wrap .pic-each').html(html);
        } else {
            $(".upload_pic_wrap").append('<span class="pic-each">' + html + '</span>');
        }
        food_set_ops.delete_img();
    }
};

var food_set_ops = {
    init: function () {
        this.ue = null;
        this.initEditor();
        this.eventBind();
        this.delete_img()
    },
    eventBind: function () {
        var that = this;
        // 上传封面图片
        $('.upload_pic_wrap input[name=pic]').change(function () {
            $('.upload_pic_wrap').submit()
        });

        $('.wrap_food_set select[name=cat_id]').select2({
            'language': 'zh-CN',
            'width': '100%'
        });
        $('.wrap_food_set input[name=tags]').tagsInput({
            'width': 'auto',
            'height': '40px',
            'defaultText': '',
        });

        $('.wrap_food_set .save').click(function () {
            var btn_target = $(this);
            if (btn_target.hasClass('disabled')) {
                common_ops.alert('正在处理中，请不要重复提交');
                return false
            }
            var cat_id_target = $('.wrap_food_set select[name=cat_id]');
            var cat_id = cat_id_target.val();

            var food_name_target = $('.wrap_food_set input[name=name]');
            var food_name = food_name_target.val();

            var price_target = $('.wrap_food_set input[name=price]');
            var price = price_target.val();

            var summary = $.trim(that.ue.getContent());

            var tags_target = $('.wrap_food_set input[name=tags]');
            var tags = $.trim(tags_target.val());

            var stock_target = $('.wrap_food_set input[name=stock]');
            var stock = stock_target.val();

            if (cat_id == 0) {
                common_ops.tip('请选择美食分类', cat_id_target);
                return false
            }
            if (!food_name || food_name.length < 1) {
                common_ops.tip('请输入美食名称', food_name_target);
                return false
            }
            // var regPrice = /^[1-9][0-9]*([\.][0-9]{1,2})?$/;
            var regPrice = /^(0([\.][0-9]{1,2})?|[1-9][0-9]*([\.][0-9]{1,2})?)$/;
            if (!regPrice.test(price)) {
                common_ops.tip('请输入符合规范的售卖价格', price_target);
                return false
            }

            //校验是否上传图片
            if ($(".wrap_food_set .pic-each").size() < 1) {
                common_ops.alert("请上传封面图");
                return false
            }
            if (summary.length < 1) {
                common_ops.alert('请输入美食描述');
                return false
            }
            var regStock = /^(0|[1-9][0-9]*)$/;
            if (!regStock.test(stock)) {
                common_ops.tip('库存值为整数类型', stock_target);
                return false
            }
            if (!tags || tags.length < 1) {
                common_ops.alert('请输入美食标签');
                return false
            }

            btn_target.addClass('disabled');

            //获取图片的键值
            pic = $(".upload_pic_wrap .pic-each .del_image").attr('data');
            //获取用户的id值
            id = $('.wrap_food_set input[name=id]').val();

            var data = {
                'id': id, 'cat_id': cat_id, 'food_name': food_name, 'price': price,
                'pic': pic, 'summary': summary, 'tags': tags, 'stock': stock
            };

            $.ajax({
                url: common_ops.buildUrl('/food/set'),
                data: data,
                type: 'POST',
                dataType: 'json',
                success: function (res) {
                    btn_target.removeClass('disabled');
                    var callback = null;
                    if(res.code === 200){
                        callback = function () {
                            window.location.href = common_ops.buildUrl('/food/index')
                        };
                        common_ops.alert('操作成功！',callback)
                    }
                }

            })

        })

    },
    initEditor: function () {
        var that = this;
        that.ue = UE.getEditor('container', {
            toolbars: [
                ['undo', 'redo', '|', 'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight'],
                ['customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'directionalityltr', 'directionalityrtl', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|', 'link', 'unlink'],
                ['imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'insertimage', 'insertvideo', '|', 'horizontal', 'spechars', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols']
            ],
            enableAutoSave: true,
            saveInterval: 60000,
            elementPathEnabled: false, //是否启用元素路径，默认是显示
            zIndex: 4,
            serverUrl: common_ops.buildUrl('/upload/ueditor')
        });
    },
    delete_img: function () {
        // unbind() 方法移除被选元素的事件处理程序。
        //删除被选元素（及其子元素）
        $(".upload_pic_wrap .del_image").unbind().click(function () {
            $(this).parent().remove()
        })
    }
};


$(document).ready(function () {
    food_set_ops.init()
});